package org.jeecg.modules.bj.util;

import cn.afterturn.easypoi.entity.ImageEntity;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.util.CellRangeAddress;

import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.modules.bj.service.impl.BjCreateFileServiceImpl;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

import static org.apache.poi.ss.usermodel.ClientAnchor.AnchorType.MOVE_DONT_RESIZE;

public class ExcelExportUtils {

	/**
	 * 表头名称
	 *
	 * @param headerStyle
	 * @param headerName
	 * @param row
	 */
	/*public static void header(XSSFCellStyle headerStyle, String headerName, Row row) {
		Map<String, String> rowMap = FormBaseName.backExportRowMap(headerName);
		// 准备迭代
		for (Map.Entry<String, String> map : rowMap.entrySet()) {
//			System.out.println("header__" + map);
			Cell cell = row.createCell(Integer.parseInt(map.getKey().toString()));
			cell.setCellStyle(headerStyle);
			cell.setCellValue(map.getValue());
		}

	}*/
	/**
	 * 自定义表头名称
	 * @param headerStyle 样式
	 * @param
	 * @param sheet
	 * @param rows 行数
	 * @param
	 * @return
	 */
	public static Row customHeader(XSSFCellStyle headerStyle, Sheet sheet,int rows,Map<String, String> rowMap) {
			Row row = sheet.createRow(rows);
			/*for (Map.Entry<String, String> map : cellMap.entrySet()) {
				Cell cell = row.createCell(Integer.parseInt(map.getKey()));
				cell.setCellStyle(headerStyle);
				cell.setCellValue(map.getValue());
			}*/
			for (Map.Entry<String, String> map : rowMap.entrySet()) {
				Cell cell = row.createCell(Integer.parseInt(map.getKey()));
				cell.setCellStyle(headerStyle);
				cell.setCellValue(map.getValue());
				sheet.setColumnWidth(Integer.parseInt(map.getKey()),
					sheet.getColumnWidth(Integer.parseInt(map.getKey())) );
			}
			return row;

	}

	public static Row customHeaderPicture(SXSSFWorkbook workbook,int row, Sheet sheet,Map<String, BufferedImage> cellMap) {
		String filePath = BjCreateFileServiceImpl.class.getClassLoader().getResource("test.jpeg").getFile();
		/*Row backrow = sheet.createRow(row);*/
//		backrow.setHeight((short)(12*200));
		/*backrow.setHeight((short)(10*256));
		System.out.println(backrow.getHeight());*/

		BufferedImage bufferImg;
		try {
			for(String key : cellMap.keySet()){
				bufferImg = ImageIO.read(new File(filePath));
				ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
				//BufferedImage bufferImg = cellMap.get(entry.getValue()); //图片
				// 将图片写入流中
				ImageIO.write(bufferImg, "png", byteArrayOut);
				// 利用HSSFPatriarch将图片写入EXCEL
				Drawing<?> patriarch = sheet.createDrawingPatriarch();
				//图片一导出到单元格B2中
				XSSFClientAnchor anchor;
				if ("usertask1".equals(key)){
					anchor = new XSSFClientAnchor(400000, 300000, 400000, -300000, 1, row-1, 3, row);

//					anchor = new XSSFClientAnchor(100, 100, 100, 100, 2, row-1, 3, row);
				}else if("usertask2".equals(key)){
					anchor = new XSSFClientAnchor(400000, 300000, 400000, -300000,  4, row-1, 6, row);
				}else if("usertask3".equals(key)){
					anchor = new XSSFClientAnchor(400000, 300000, 400000, -300000,  7, row-1, 9, row);
				}else if("usertask4".equals(key)){
					anchor = new XSSFClientAnchor(400000, 300000, 400000, -300000, 10, row-1, 12, row);
				}
				else{
					anchor = new XSSFClientAnchor();
				}
				anchor.setAnchorType(MOVE_DONT_RESIZE);

				//插入图片
				patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

			}


		} catch (IOException e) {
			System.err.println(e);
			e.printStackTrace();
		}

		/*for (Map.Entry<String, BufferedImage> entry : cellMap.entrySet()) {
				//将图片读到BufferedImage
				try {
					String filePath = BjCreateFileServiceImpl.class.getClassLoader().getResource("test.jpeg").getFile();
					BufferedImage bufferImg = ImageIO.read(new File(filePath));
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
					//BufferedImage bufferImg = cellMap.get(entry.getValue()); //图片
					// 将图片写入流中
					ImageIO.write(bufferImg, "png", byteArrayOut);
					// 利用HSSFPatriarch将图片写入EXCEL
					Drawing<?> patriarch = sheet.createDrawingPatriarch();
					//图片一导出到单元格B2中
					XSSFClientAnchor anchor = new XSSFClientAnchor(200, 100, 300, 600,
							(short) 50, 50, (short) 10, 30);
					// 插入图片
					patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut
							.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
				} catch (IOException e) {
					e.printStackTrace();
				}
		}*/
		return null;

	}

	/**
	 * 合并单元格
	 *
	 * @param
	 * @param
	 */
	/*public static void merge(String headerName, Sheet sheet) {

		Map<String, String> rowMap = FormBaseName.backExportMergeMap(headerName);
		// 准备迭代
		for (Map.Entry<String, String> map : rowMap.entrySet()) {
//			System.out.println("merge__" + map);

			String[] temp = map.getValue().split(",");
			Integer startrow = Integer.parseInt(temp[0]);// 开始行数
			Integer overrow = Integer.parseInt(temp[1]);// 结束行数
			Integer startcol = Integer.parseInt(temp[2]);// 开始列
			Integer overcol = Integer.parseInt(temp[3]);// 结束列
			sheet.addMergedRegion(new CellRangeAddress(startrow, overrow, startcol, overcol));

		}
	}*/
	public static void customMerge(SXSSFWorkbook wb,Sheet sheet,List<String> rowList) {

		// 准备迭代
		for(String rowContent : rowList){
			String[] temp = rowContent.split(",");
			Integer startrow = Integer.parseInt(temp[0]);// 开始行数
			Integer overrow = Integer.parseInt(temp[1]);// 结束行数
			Integer startcol = Integer.parseInt(temp[2]);// 开始列
			Integer overcol = Integer.parseInt(temp[3]);// 结束列
			CellRangeAddress cellRangeAddress =new CellRangeAddress(startrow, overrow, startcol, overcol);
			sheet.addMergedRegion(cellRangeAddress);
		}
		/*RegionUtil.setBorderBottom(1, cellRangeAddress, sheet, wb);//下边框
		    RegionUtil.setBorderLeft(1, cellRangeAddress, sheet, wb);//左边框
		    RegionUtil.setBorderRight(1, cellRangeAddress, sheet, wb);//右边框
		    RegionUtil.setBorderTop(1, cellRangeAddress, sheet, wb);//上边框*/
	}

	/**
	 * 单元格宽度
	 *
	 * @param headerName
	 * @param sheet
	 */
	public static void columnWidth(String headerName, Sheet sheet) {

		Map<String, String> rowMap = FormBaseName.backExportColumnWidthMap(headerName);
		// 准备迭代
		for (Map.Entry<String, String> map : rowMap.entrySet()) {
			sheet.setColumnWidth(Integer.parseInt(map.getKey()),
					Integer.parseInt(map.getValue()) * 256);
		}
	}



	/**
	 * 自定义表头
	 * @param headerStyle
	 * @param headerName
	 * @param
	 * @param sheet
	 */
	public static Row customHeader2(XSSFCellStyle headerStyle, String headerName, int rows, Sheet sheet) {
		Row row = sheet.createRow(rows);

		Map<String, String> rowMap = FormBaseName.backExportRowMap2(headerName);
		// 准备迭代
		for (Map.Entry<String, String> map : rowMap.entrySet()) {
			Cell cell = row.createCell(Integer.parseInt(map.getKey()));
			cell.setCellStyle(headerStyle);
			cell.setCellValue(map.getValue());
			sheet.setColumnWidth(Integer.parseInt(map.getKey()),
					sheet.getColumnWidth(Integer.parseInt(map.getKey())) * 22 / 10);
		}
		return row;

	}



	public static int customDataRow(List<Map<String,Object>> list, String rowName, XSSFCellStyle rowStyle, Sheet sheet,int rows) {
		int a = rows;
		if (list != null) {
			try {
				for (int i = 0; i < list.size(); i++) {
					Row contentRow = sheet.createRow(i + rows);// 填充类容,从第3行开始,1-2行表头
					a=a+1;
					Map<String, String> rowMap = FormBaseName.backExportDataRowMap(rowName);
					for (Map.Entry<String, String> map : rowMap.entrySet()) {
						Cell cell = contentRow.createCell(Integer.parseInt(map.getKey()));
						cell.setCellStyle(rowStyle);
						for (String key : list.get(i).keySet()){
							if (map.getValue().equals(key)){
								cell.setCellValue(list.get(i).get(key).toString());
							}
						}

					}
				}

			} catch (Exception e) {
				throw new IllegalArgumentException("field can't match the key!");
			}
			return a;
		}
		return 0;
	}


	// 把一个字符串的第一个字母大写、效率是最高的、
	private static String getMethodName(String fildeName) throws Exception {
		byte[] items = fildeName.getBytes();
		items[0] = (byte) ((char) items[0] - 'a' + 'A');
		return new String(items);
	}

}
